package idiolect.helpers;

import idiolect.core.IOUtil;

import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;

public class LingvoTranscriptionHelper extends AbstractHelper {
    private static final String STARTMARKER = "<span>[</span><span class=\"uni\">";
    private static final String STOPMARKER = "</span>";

    public LingvoTranscriptionHelper(String request, ResponseAcceptor requestor, int taskID) {
        super(request, requestor, taskID);
    }

    //http://lingvo.yandex.ru/en?text=cyan&from=os&st_translate=on
    public void run() {
        try {
            String page = new String(IOUtil.getContent(new URL("http://lingvo.yandex.ru/en?text=" + URLEncoder.encode(request) + "&from=os&st_translate=on")), "utf-8");
            int startPos = page.indexOf(LingvoTranscriptionHelper.STARTMARKER);
            if (startPos == -1)
                throw new IOException("Transcription not found for '" + request + "'");
            int stopPos = page.indexOf(LingvoTranscriptionHelper.STOPMARKER, startPos + LingvoTranscriptionHelper.STARTMARKER.length());
            if (stopPos == -1)
                throw new IOException("Transcription not found for '" + request + "'");
            response = page.substring(startPos + LingvoTranscriptionHelper.STARTMARKER.length(), stopPos);
        } catch (IOException e) {
//            e.printStackTrace();
            response = null;
        }
    }
}
